<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>步态分析系统 - 登录</title>
    <link rel="stylesheet" href="https://unpkg.com/element-plus@2.3.8/dist/index.css">
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            background-color: #f5f7fa;
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .login-container {
            width: 400px;
            padding: 40px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }
        .login-title {
            text-align: center;
            margin-bottom: 30px;
            color: #409EFF;
        }
        .login-form {
            margin-top: 20px;
        }
        .login-button {
            width: 100%;
        }
        .register-link {
            text-align: center;
            margin-top: 20px;
        }
        .button-group {
            display: flex;
            gap: 10px;
            margin-top: 20px;
        }
        .button-group .el-button {
            flex: 1;
        }
    </style>
</head>
<body>
    <div id="app">
        <div class="login-container">
            <h2 class="login-title">步态分析系统</h2>
            <el-form :model="loginForm" :rules="rules" ref="loginFormRef" class="login-form">
                <el-form-item prop="username">
                    <el-input v-model="loginForm.username" placeholder="用户名">
                        <template #prefix>
                            <el-icon><User /></el-icon>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input v-model="loginForm.password" type="password" placeholder="密码">
                        <template #prefix>
                            <el-icon><Lock /></el-icon>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item prop="userType">
                    <el-select v-model="loginForm.userType" placeholder="请选择用户类型" style="width: 100%;">
                        <el-option label="普通用户" value="user"></el-option>
                        <el-option label="管理员" value="admin"></el-option>
                    </el-select>
                </el-form-item>
                <div class="button-group">
                    <el-button type="primary" @click="handleLogin" :loading="loading">登录</el-button>
                    <el-button type="success" @click="showRegisterDialog">注册</el-button>
                </div>
            </el-form>
        </div>

        <!-- 注册对话框 -->
        <el-dialog v-model="registerDialogVisible" title="用户注册" width="400px">
            <el-form :model="registerForm" :rules="registerRules" ref="registerFormRef" label-width="100px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="registerForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="registerForm.password" type="password"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                    <el-input v-model="registerForm.confirmPassword" type="password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="registerForm.email"></el-input>
                </el-form-item>
                <el-form-item label="用户类型" prop="userType">
                    <el-select v-model="registerForm.userType" placeholder="请选择用户类型" style="width: 100%;">
                        <el-option label="普通用户" value="user"></el-option>
                        <el-option label="管理员" value="admin"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="registerDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleRegister" :loading="registerLoading">注册</el-button>
                </span>
            </template>
        </el-dialog>
    </div>

    <script src="https://unpkg.com/vue@3.3.4/dist/vue.global.js"></script>
    <script src="https://unpkg.com/element-plus@2.3.8"></script>
    <script src="https://unpkg.com/@element-plus/icons-vue"></script>
    <script src="https://unpkg.com/axios@1.4.0/dist/axios.min.js"></script>

    <script>
        const { createApp, ref, onMounted } = Vue;
        const { ElMessage } = ElementPlus;

        const app = createApp({
            setup() {
                const loginFormRef = ref(null);
                const loginForm = ref({
                    username: '',
                    password: '',
                    userType: 'user'
                });
                const loading = ref(false);
                const registerLoading = ref(false);

                const registerFormRef = ref(null);
                const registerForm = ref({
                    username: '',
                    password: '',
                    confirmPassword: '',
                    email: '',
                    userType: 'user'
                });
                const registerDialogVisible = ref(false);

                // 配置axios
                const setupAxios = () => {
                    // 根据当前环境确定服务器地址
                    const getBaseURL = () => {
                        const protocol = window.location.protocol;
                        const hostname = window.location.hostname;
                        const port = window.location.port;
                        
                        // VS Code Live Server 环境
                        if (port === '5500') {
                            return 'http://localhost:5000';
                        }
                        // 本地文件系统
                        if (protocol === 'file:') {
                            return 'http://localhost:5000';
                        }
                        // 其他情况（如果在同一域名下）
                        return `${protocol}//${hostname}:5000`;
                    };

                    axios.defaults.baseURL = getBaseURL();
                    axios.defaults.timeout = 10000; // 设置10秒超时
                    axios.defaults.withCredentials = false;  // 禁用 credentials

                    // 请求拦截器
                    axios.interceptors.request.use(
                        config => {
                            console.log('Current environment:', {
                                protocol: window.location.protocol,
                                hostname: window.location.hostname,
                                port: window.location.port
                            });
                            
                            const token = localStorage.getItem('token');
                            if (token) {
                                config.headers.Authorization = `Bearer ${token}`;
                            }
                            
                            // 确保URL是完整的
                            if (!config.url.startsWith('http')) {
                                config.url = axios.defaults.baseURL + config.url;
                            }
                            
                            console.log('Sending request to:', config.url);
                            return config;
                        },
                        error => {
                            console.error('Request error:', error);
                            return Promise.reject(error);
                        }
                    );

                    // 响应拦截器
                    axios.interceptors.response.use(
                        response => {
                            console.log('Received response:', response);
                            return response;
                        },
                        error => {
                            console.error('Response error:', error);
                            if (error.response) {
                                const status = error.response.status;
                                const message = error.response.data?.message || '未知错误';
                                
                                switch (status) {
                                    case 400:
                                        ElMessage.error(message || '请求参数错误');
                                        break;
                                    case 401:
                                        ElMessage.error(message || '用户名或密码错误');
                                        break;
                                    case 403:
                                        ElMessage.error(message || '权限不足');
                                        break;
                                    case 500:
                                        ElMessage.error(message || '服务器内部错误');
                                        break;
                                    default:
                                        ElMessage.error(message || '请求失败');
                                }
                            } else if (error.code === 'ECONNABORTED') {
                                ElMessage.error('请求超时，请检查网络连接');
                            } else if (error.message?.includes('Network Error')) {
                                ElMessage.error('无法连接到服务器，请确保服务器已启动');
                            } else if (error instanceof DOMException && error.message.includes('Invalid URL')) {
                                ElMessage.error('API服务器地址配置错误，请联系管理员');
                            } else {
                                ElMessage.error('请求失败，请稍后重试');
                            }
                            return Promise.reject(error);
                        }
                    );
                };

                const handleLogin = async () => {
                    if (!loginFormRef.value) return;
                    
                    try {
                        loading.value = true;
                        await loginFormRef.value.validate();
                        
                        console.log('Attempting login with:', {
                            username: loginForm.value.username,
                            userType: loginForm.value.userType
                        });

                        const response = await axios.post('/login', {
                            username: loginForm.value.username,
                            password: loginForm.value.password,
                            userType: loginForm.value.userType
                        });
                        
                        console.log('Login response:', response);
                        
                        const { token, is_admin, username, message } = response.data;
                        
                        if (!token) {
                            throw new Error('服务器未返回有效的认证令牌');
                        }
                        
                        // 保存认证信息
                        localStorage.setItem('token', token);
                        localStorage.setItem('isAdmin', is_admin ? 'true' : 'false');
                        localStorage.setItem('username', username);
                        
                        // 显示成功消息
                        ElMessage.success(message || '登录成功');
                        
                        // 延迟跳转，让用户看到成功消息
                        setTimeout(() => {
                            // 根据用户类型重定向到不同页面
                            if (is_admin) {
                                window.location.href = 'admin.html';
                            } else {
                                window.location.href = 'index.html';
                            }
                        }, 1000);
                    } catch (error) {
                        console.error('Login error:', error);
                        // 错误处理已经在响应拦截器中完成
                    } finally {
                        loading.value = false;
                    }
                };

                const showRegisterDialog = () => {
                    registerDialogVisible.value = true;
                };

                const handleRegister = async () => {
                    if (!registerFormRef.value) return;
                    
                    try {
                        registerLoading.value = true;
                        await registerFormRef.value.validate();
                        const response = await axios.post('/register', {
                            username: registerForm.value.username,
                            password: registerForm.value.password,
                            email: registerForm.value.email,
                            is_admin: registerForm.value.userType === 'admin'
                        });

                        ElMessage.success('注册成功，请登录');
                        registerDialogVisible.value = false;
                        // 清空注册表单
                        registerForm.value = {
                            username: '',
                            password: '',
                            confirmPassword: '',
                            email: '',
                            userType: 'user'
                        };
                    } catch (error) {
                        console.error('Register error:', error);
                        if (error.response) {
                            ElMessage.error(error.response.data.message || '注册失败');
                        } else {
                            ElMessage.error('注册失败，请稍后重试');
                        }
                    } finally {
                        registerLoading.value = false;
                    }
                };

                const validatePass = (rule, value, callback) => {
                    if (value === '') {
                        callback(new Error('请输入密码'));
                    } else {
                        if (registerForm.value.confirmPassword !== '') {
                            registerFormRef.value?.validateField('confirmPassword');
                        }
                        callback();
                    }
                };

                const validatePass2 = (rule, value, callback) => {
                    if (value === '') {
                        callback(new Error('请再次输入密码'));
                    } else if (value !== registerForm.value.password) {
                        callback(new Error('两次输入密码不一致!'));
                    } else {
                        callback();
                    }
                };

                const rules = {
                    username: [
                        { required: true, message: '请输入用户名', trigger: 'blur' }
                    ],
                    password: [
                        { required: true, message: '请输入密码', trigger: 'blur' }
                    ],
                    userType: [
                        { required: true, message: '请选择用户类型', trigger: 'change' }
                    ]
                };

                const registerRules = {
                    username: [
                        { required: true, message: '请输入用户名', trigger: 'blur' },
                        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
                    ],
                    password: [
                        { required: true, validator: validatePass, trigger: 'blur' },
                        { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
                    ],
                    confirmPassword: [
                        { required: true, validator: validatePass2, trigger: 'blur' }
                    ],
                    email: [
                        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
                    ],
                    userType: [
                        { required: true, message: '请选择用户类型', trigger: 'change' }
                    ]
                };

                onMounted(async () => {
                    setupAxios();
                    // 检查是否已经登录
                    const token = localStorage.getItem('token');
                    if (token) {
                        try {
                            // 验证token是否有效
                            const response = await axios.get('/api/verify_token', {
                                headers: {
                                    'Authorization': `Bearer ${token}`
                                }
                            });
                            
                            // 如果token验证成功，再进行重定向
                            const isAdmin = localStorage.getItem('isAdmin') === 'true';
                            if (isAdmin) {
                                window.location.href = 'admin.html';
                            } else {
                                window.location.href = 'index.html';
                            }
                        } catch (error) {
                            // 如果token无效，清除所有存储的认证信息
                            localStorage.removeItem('token');
                            localStorage.removeItem('isAdmin');
                            localStorage.removeItem('username');
                            console.log('Invalid token, cleared authentication data');
                        }
                    }
                });

                return {
                    loginFormRef,
                    loginForm,
                    registerFormRef,
                    registerForm,
                    registerDialogVisible,
                    rules,
                    registerRules,
                    loading,
                    registerLoading,
                    handleLogin,
                    showRegisterDialog,
                    handleRegister
                };
            }
        });

        app.use(ElementPlus);
        for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
            app.component(key, component);
        }

        app.mount('#app');
    </script>
</body>
</html> 